import { createSlice } from "@reduxjs/toolkit";
import { RootState } from "store";
/**
 * 主要内容区域
 **/
export interface contentObj {
  id?: number;
  imgUrl: string;
  title: string;
  author: string;
  tip: string;
  original: number;

  tag: string;
  createTime?: number;
  fileUrl?: string;
  isnote: number;
  demoUrl?: string;
}

interface State {
  content: contentObj[];
  isShowEditModal: boolean;
  editContentId: number | undefined;
}
const initialState: State = {
  content: [],
  isShowEditModal: false,
  editContentId: undefined,
};

export const editSlice = createSlice({
  name: "edit",
  initialState,
  reducers: {
    setContent(state, action) {
      state.content = action.payload;
    },
    updateContent(state, action) {
      const content = action.payload as contentObj;
      state.content = state.content.map((sc) =>
        content.id === sc.id ? content : sc
      );
    },
    deleteContent(state, action) {
      state.content = state.content.filter((c) => c.id !== action.payload);
    },
    onSetEditContentId(state, action) {
      state.editContentId = action.payload;
    },
    onShowEditModal(state) {
      state.isShowEditModal = true;
    },
    onCloseEditModal(state) {
      state.isShowEditModal = false;
    },
  },
});
export const editActions = editSlice.actions;

export const selectContent = (state: RootState) => {
  const { content } = state.edit;
  const { tag } = state.main;
  if (tag === "") {
    return content;
  } else {
    return content.filter((c) => !!~c.tag.indexOf(tag));
  }
};

export const selectEditContent = (state: RootState) => {
  const ret = state.edit.content.filter(
    (content) => content.id === state.edit.editContentId
  );

  return ret.length > 0 ? ret[0] : undefined;
};

export const selectIsShowEditModal = (state: RootState) => {
  return state.edit.isShowEditModal;
};

export const selectEditContentId = (state: RootState) =>
  state.edit.editContentId;

// 获取所有标签
export const selectAllContentTag = (state: RootState) => [
  ...new Set(state.edit.content.map((c) => c.tag.split(",")).flat(1)),
];
